import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
// import { getInitMenus } from '@/api/login'
// import layout from '@/layout'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
    // asyncRoutes: [], // 当前用户拥有的权限列表，构建动态列表
    // btnPermissions: []// 页面按钮级别的路由权限
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
  // SET_ASYNC_ROUTES(state, asyncRoutes) {
  //   state.asyncRoutes = asyncRoutes
  // },
  // REMOVE_USERINFO(state) {
  //   // 路由重置
  //   state.asyncRoutes = []
  //   state.btnPermissions = []
  // },
  // RESET_BTN_PERMI(state, permissions) {
  //   state.btnPermissions = permissions
  // },
  // CLEAR_BTN_PEREMI(state) {
  //   state.btnPermissions = []
  // }

}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
  // getInitMenus({ commit, state }) {
  //   // 构建路由权限
  //   function buildRoutes(routes, pList, pRouter) {
  //     for (var i = 0; i < pList.length; i++) {
  //       var p = pList[i]
  //       if (p.style === 1) {
  //         var route = {
  //           path: p.path,
  //           name: p.name
  //         }
  //         // 顶级路由
  //         if (p.pid === '0') {
  //           route.component = layout
  //         } else {
  //           var path = p.component.replace(/^@\/views/, '')
  //           // 闭包加立即执行
  //           route.component = (path => {
  //             return (resolve) => {
  //               // require 虽然支持变量 但必须有一个根问价夹
  //               require([`@/views${path}`], resolve)
  //             }
  //           })(path)
  //         }
  //         // 重定向
  //         if (p.redirect) {
  //           route.redirect = p.redirect
  //         }
  //         if (p.meta) {
  //           route.meta = JSON.parse(p.meta)
  //         }
  //         if (p.hidden) {
  //           route.hidden = true
  //         }
  //         if (p.alwaysShow) {
  //           route.alwaysShow = true
  //         }
  //         routes.push(route)
  //         if (p.children && p.children.length > 0) {
  //           route.children = []
  //           buildRoutes(route.children, p.children, route)
  //         }
  //       } else {
  //         delete pRouter.children
  //         if (!pRouter.meta.permissionValues) {
  //           pRouter.meta.permissionValues = []
  //         }
  //         pRouter.meta.permissionValues.push(p.permissionValue)
  //       }
  //     }
  //   }
  //   return new Promise((resolve, reject) => {
  //     getInitMenus().then(res => {
  //       if (res.success) {
  //         var routes = []
  //         var pList = res.data.permissionList
  //         // 构建动态路由
  //         buildRoutes(routes, pList)
  //         routes.push({ path: '*', redirect: '/404', hidden: true })
  //         // 用于储存新增的动态路由 配合sidebar 生成菜单
  //         commit('SET_ASYNC_ROUTES', routes)
  //         resetRouter()
  //         // 构建完整路由
  //         router.addRoutes(routes)
  //         resolve()
  //       } else {
  //         if (res.code === 2001) {
  //           reject(res)
  //         }
  //       }
  //     })
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

